package com.cloud.xml;

import lombok.SneakyThrows;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

public class Dom4jExample {

    @SneakyThrows
    public static void main(String[] args) {
        try {
            // 读取resource文件夹下
            InputStream inputStream = Dom4jExample.class.getClassLoader().getResourceAsStream("example.xml");
            if (inputStream == null) {
                throw new FileNotFoundException("File not found: example.xml");
            }
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);

            // 获取根元素
            Element root = document.getRootElement();
            System.out.println("Root Element: " + root.getName());

            // 获取所有 employee 元素
            List<Element> employees = root.elements("employee");

            for (Element employee : employees) {
                String id = employee.attributeValue("id");
                String name = employee.elementText("name");
                String age = employee.elementText("age");
                String department = employee.elementText("department");

                System.out.println("Employee ID: " + id);
                System.out.println("Name: " + name);
                System.out.println("Age: " + age);
                System.out.println("Department: " + department);
                System.out.println("--------------------------");
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}
